const fse = require('fs-extra');
const { mParser, mDownloader, mConverter, mIndicator } = require('node-m3u8-to-mp4');
const path = require('path');
const http = require('http');
const indexService = require('../service/index.service');
const { deleteRecordsFn } = require('./tencentcloud');

const automationDownload = (obj, index) => {
  indexService.getFileInfo('0', async (res) => {
    for (let index = 0; index < res.length; index++) {
      // if (index == 1) return;
      const { file_id, start_time, video_url, type } = res[index];
      const ymd = formatTimestamp(start_time);
      const directoryPath = path.join(__dirname, '..', '.downloads', ymd); // 指定的路径
      if (!fse.existsSync(directoryPath)) {
        // 路径不存在，创建路径
        fse.mkdirSync(directoryPath, { recursive: true });
      }

      try {
        switch (type) {
          case 'mp4':
            const fileUrl = video_url; // 文件路径
            const filePath = path.join(__dirname, '..', '.downloads', ymd, `${file_id}.mp4`); // 指定的文件名
            const file = fse.createWriteStream(filePath);
            http
              .get(fileUrl, (response) => {
                const totalSize = response.headers['content-length'];
                let downloadedSize = 0; // 已下载的文件大小
                response.on('data', (data) => {
                  downloadedSize += data.length;
                  const progress = (downloadedSize / totalSize) * 100;
                  console.log(`下载进度: ${progress.toFixed(2)}%`);
                });
                response.pipe(file);
                file.on('finish', () => {
                  file.close(async () => {
                    console.log('🚀 ~ file: utils.js:22 ~ file.close ~ success:Mp4成功下载');
                    const mp4L = {
                      move_video_url: `/${ymd}/${file_id}.mp4`,
                      status: '1',
                      move_time: getCurrentDateTime(),
                      cause: '拉取成功',
                    };
                    updateRecordsFn(mp4L, file_id);

                    const deleteRes = await deleteRecordsFn(file_id);
                    const mp4L2 = {
                      status: '2',
                      cause: '删除成功',
                    };
                    if (deleteRes.RequestId) {
                      updateRecordsFn(mp4L2, file_id);
                    } else {
                      mp4L2.status = '3';
                      mp4L2.cause = '拉取成功,删除失败';
                      updateRecordsFn(mp4L2, file_id);
                    }
                  });
                });
              })
              .on('error', (err) => {
                fse.unlink(filePath, () => {
                  // updateRecordsFn(FileId, '失败', index);
                  const mp4L3 = {
                    status: '1',
                    cause: err.message || '拉取失败',
                  };
                  updateRecordsFn(mp4L3, file_id);
                  console.error('Mp4下载视频时发生错误:', err);
                });
              });
            break;

          case 'm3u8':
            mIndicator('downloading', (index, total) => {
              console.log('下载进度:' + ((index / total) * 100).toFixed(2) + '%');
            });
            const list = await mParser(video_url);
            const medias = list.map((item) => `${item.url}`);
            await mDownloader(medias, {
              targetPath: path.resolve('.temp'),
            });
            await mConverter(path.resolve('.temp'), `.downloads/${ymd}/${file_id}.mp4`);
            const m3u8L = {
              move_video_url: `/${ymd}/${file_id}.mp4`,
              status: '1',
              move_time: getCurrentDateTime(),
              cause: '拉取成功',
            };
            updateRecordsFn(m3u8L, file_id);

            const deleteRes = await deleteRecordsFn(file_id);
            const m3u8L2 = {
              status: '2',
              cause: '删除成功',
            };
            if (deleteRes.RequestId) {
              updateRecordsFn(m3u8L2, file_id);
            } else {
              m3u8L2.status = '3';
              m3u8L2.cause = '拉取成功,删除失败';
              updateRecordsFn(m3u8L2, file_id);
            }
            break;

          default:
            console.log('🚀 ~ file: utils.js:48 ~ automationDownload ~ 格式不正确:', type);
            const deleteOtherRes = await deleteRecordsFn(file_id);
            const orderL = {
              status: '2',
              cause: '删除成功',
            };
            if (deleteOtherRes.RequestId) {
              updateRecordsFn(orderL, file_id);
            } else {
              orderL.status = '3';
              orderL.cause = '删除失败';
              updateRecordsFn(orderL, file_id);
            }
            break;
        }
      } catch (error) {
        fse.removeSync(path.resolve('.temp'));
        const errorL = {
          status: '1',
          cause: error.message || '拉取失败',
        };
        updateRecordsFn(errorL, file_id);
        console.log('🚀 ~ file: index.js:19 ~ error:', error);
        continue;
      }
    }
  });
};

const updateRecordsFn = (params, file_id) => {
  indexService.updateFileInfo(params, file_id, (res) => {
    console.log('🚀 ~ indexService.updateFileInfo ~ res:', res);
  });
};

const convertToTimestamp = (standardTime) => {
  const dateObj = new Date(standardTime);
  const timestamp = Math.floor(dateObj.getTime() / 1000);
  return timestamp;
};

function compareTime(standardTime, startTime, endTime) {
  // 将标准时间、开始时间和结束时间转换为 Date 对象
  const standardDate = new Date(standardTime);
  const startDate = new Date(startTime);
  const endDate = new Date(endTime);

  // 获取标准时间、开始时间和结束时间的毫秒数
  const standardTimeMs = standardDate.getTime();
  const startTimeMs = startDate.getTime();
  const endTimeMs = endDate.getTime();

  // 比较指定时间是否在开始时间和结束时间之间
  if (startTimeMs <= standardTimeMs && standardTimeMs <= endTimeMs) {
    return true;
  } else {
    return false;
  }
}

const formatTimestamp = (timestamp) => {
  const dateObj = new Date(timestamp * 1000);
  const year = dateObj.getFullYear();
  const month = String(dateObj.getMonth() + 1).padStart(2, '0');
  const day = String(dateObj.getDate()).padStart(2, '0');
  const formattedDate = `${year}-${month}-${day}`;
  return formattedDate;
};

const getCurrentDateTime = () => {
  const currentDate = new Date();

  const year = currentDate.getFullYear();
  const month = String(currentDate.getMonth() + 1).padStart(2, '0');
  const day = String(currentDate.getDate()).padStart(2, '0');
  const hours = String(currentDate.getHours()).padStart(2, '0');
  const minutes = String(currentDate.getMinutes()).padStart(2, '0');
  const seconds = String(currentDate.getSeconds()).padStart(2, '0');

  const formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

  return formattedDateTime;
};

module.exports = {
  automationDownload,
  convertToTimestamp,
  compareTime,
};
